package com.woniu.zsd.order.config;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    // 保存所有连接的会话，使用用户 ID 映射到 WebSocketSession
    private static final Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 当客户端连接时，将 session 加入列表，并绑定用户 ID
        String userId = getUserIdFromSession(session); // 获取用户 ID 的逻辑
        userSessions.put(userId, session);
        System.out.println("新连接：" + session.getId() + "，用户 ID：" + userId);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 接收客户端消息
        String payload = message.getPayload();
        System.out.println("收到消息：" + payload);

        // 可以在这里处理消息并广播或点对点发送
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 当客户端断开连接时，移除 session
        String userId = getUserIdFromSession(session);
        userSessions.remove(userId);
        System.out.println("连接关闭：" + session.getId() + "，用户 ID：" + userId);
    }

    /**
     * 点对点消息推送
     *
     * @param userId  目标用户 ID
     * @param message 要发送的消息
     * @throws IOException 如果发送失败
     */
    public void sendPointToPointMessage(String userId, String message) throws IOException {
        WebSocketSession targetSession = userSessions.get(userId);
        if (targetSession != null && targetSession.isOpen()) {
            targetSession.sendMessage(new TextMessage(message));
            System.out.println("消息已发送给用户 ID：" + userId + "，内容：" + message);
        } else {
            System.out.println("无法发送消息，用户 ID：" + userId + " 未连接");
        }
    }

    /**
     * 根据 session 获取用户 ID
     * （假设用户 ID 存储在 session 的属性中）
     *
     * @param session WebSocketSession
     * @return 用户 ID
     */
    private String getUserIdFromSession(WebSocketSession session) {
        Map<String, Object> attributes = session.getAttributes();
        return (String) attributes.get("userId"); // 假设前端传递了 userId 属性
    }
}